using IQIGame.Onigao.GamePlay;

namespace IQIGame.Onigao.Logic
{
    /// <summary>
    /// 乘坐电梯
    /// 参数组1：1：电梯tag（0表示当前实体）
    /// </summary>
    public class ExecUseElevator : BaseServiceExecution
    {
        public override void Execute(LevelRegion region, LevelPlayer player)
        {
            var config = _config as ExecParamUseElevtor;
            if (!config.tagOrMcid.TryGetValue(triggerEntity, out int tagOrMcid))
            {
                LogicLog.LogError("无法获取到tagOrMcid.");
                return;
            }
            //只有电梯能触发该执行
            LevelEntity elevator = tagOrMcid == 0 ? triggerEntity : region.GetEntityByTagOrMcid(tagOrMcid);

            if (elevator == null)
            {
                LogicLog.LogError($"找不到电梯:{tagOrMcid}.");
                return;
            }

            if (region.IsRunningElevator(elevator.id))
            {
                return;
            }
            EntityParamElevator elevatorParam = elevator.GetDynamicParam(EntityDynamicParamType.Elevator) as EntityParamElevator;
            EntityPropElevator elevatorProp = elevator.GetDynamicProperty(EntityDynamicPropertyType.Elevator) as EntityPropElevator;

            int curFloor = elevatorProp.curFloor;

            //目标层逻辑：从当前层+1开始向上环形遍历所有楼层，取第一个激活的楼层。
            int targetFloor = curFloor + 1;
            int floorCount = elevatorParam.floors.Count;
            for (int i = 0; i < floorCount; i++)
            {
                int realFloor = (targetFloor + i) % floorCount;
                if (elevatorProp.floorActiveList[realFloor])
                {
                    targetFloor = realFloor;
                    break;
                }
            }

            if (targetFloor == curFloor)
            {
                LogicLog.LogError("除了当前层以外，没有找到其他的已激活楼层。");
                return;
            }

            region.StartElevator(player, elevator, targetFloor, true);
        }
    }
}
